import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from "./register.module.css";
import SHA512 from 'crypto-js/sha512';
import axios from 'axios';
import { Toast } from 'antd-mobile';

// 设置axios基础URL和超时时间
const API_BASE_URL = 'http://localhost:3000'; // 根据实际后端地址修改
axios.defaults.baseURL = API_BASE_URL;
axios.defaults.timeout = 15000; // 设置请求超时时间为15秒

// 添加请求拦截器
axios.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么
        return config;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
axios.interceptors.response.use(
    response => {
        // 对响应数据做点什么
        return response;
    },
    error => {
        // 对响应错误做点什么
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
            // 请求超时
            console.log('请求超时，请检查网络连接');
        } else if (!error.response) {
            // 网络错误
            console.log('网络错误，请检查网络连接');
        }
        return Promise.reject(error);
    }
);

export default function Register() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);
    const [emailError, setEmailError] = useState("");
    const [passwordError, setPasswordError] = useState("");
    const [confirmPasswordError, setConfirmPasswordError] = useState("");
    const [verificationCode, setVerificationCode] = useState("");
    const [codeError, setCodeError] = useState("");
    const [isCodeSent, setIsCodeSent] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isSendingCode, setIsSendingCode] = useState(false);
    const [retryCount, setRetryCount] = useState(0);
    const [touched, setTouched] = useState({
        email: false,
        password: false,
        confirmPassword: false,
        code: false
    });
    const [formSubmitted, setFormSubmitted] = useState(false);
    const navigate = useNavigate();

    // 验证邮箱格式
    const validateEmail = (email) => {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(String(email).toLowerCase());
    };

    // 验证密码格式
    const validatePassword = (password) => {
        return password.length >= 6;
    };

    // 验证两次密码是否一致
    const validatePasswordsMatch = () => {
        return password === confirmPassword;
    };

    // 检查邮箱
    useEffect(() => {
        // 只有当邮箱输入框被触碰过或表单提交过，才进行验证
        if ((touched.email || formSubmitted) && email && !validateEmail(email)) {
            setEmailError("无效的邮件地址！！！");
        } else {
            setEmailError("");
        }
    }, [email, touched.email, formSubmitted]);

    // 检查密码
    useEffect(() => {
        // 只有当密码输入框被触碰过或表单提交过，才进行验证
        if ((touched.password || formSubmitted) && password && !validatePassword(password)) {
            setPasswordError("密码长度至少为6位");
        } else {
            setPasswordError("");
        }
    }, [password, touched.password, formSubmitted]);

    // 检查确认密码
    useEffect(() => {
        // 只有当确认密码输入框被触碰过或表单提交过，才进行验证
        if ((touched.confirmPassword || formSubmitted) && confirmPassword && !validatePasswordsMatch()) {
            setConfirmPasswordError("两次输入的密码不一致");
        } else {
            setConfirmPasswordError("");
        }
    }, [confirmPassword, password, touched.confirmPassword, formSubmitted]);

    // 倒计时处理
    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
            return () => clearTimeout(timer);
        }
    }, [countdown]);

    const handleBlur = (field) => {
        setTouched(prev => ({ ...prev, [field]: true }));
    };

    // 发送验证码
    const handleSendCode = async () => {
        // 验证邮箱
        if (!validateEmail(email)) {
            setEmailError("无效的邮件地址！！！");
            return;
        }

        try {
            setIsSendingCode(true);
            setCodeError("");
            
            const response = await axios.post('/send-register-code', { email });
            
            if (response.data.code === 200) {
                setIsCodeSent(true);
                setCountdown(60); // 设置60秒倒计时
                setCodeError("");
                setRetryCount(0); // 重置重试计数
            }
        } catch (error) {
            console.error('发送验证码失败:', error);
            setRetryCount(prev => prev + 1);
            
            if (error.response && error.response.data) {
                setCodeError(error.response.data.message || '发送验证码失败');
            } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
                setCodeError('请求超时，请检查网络连接');
            } else if (!error.response) {
                setCodeError('网络错误，请检查网络连接');
            } else {
                setCodeError('发送验证码失败，请稍后重试');
            }
        } finally {
            setIsSendingCode(false);
        }
    };

    const handleRegister = async (e) => {
        e.preventDefault();
        setFormSubmitted(true);
        
        // 验证邮箱
        if (!validateEmail(email)) {
            setEmailError("无效的邮件地址！！！");
            return;
        }
        
        // 验证密码
        if (!validatePassword(password)) {
            setPasswordError("密码长度至少为6位");
            return;
        }
        
        // 验证密码一致性
        if (!validatePasswordsMatch()) {
            setConfirmPasswordError("两次输入的密码不一致");
            return;
        }

        // 验证验证码
        if (!verificationCode) {
            setCodeError("请输入验证码");
            return;
        }

        const hashedPassword = SHA512(password).toString();
        
        try {
            setIsSubmitting(true);
            // 清除所有错误信息
            setEmailError("");
            setPasswordError("");
            setConfirmPasswordError("");
            setCodeError("");
            
            // 注册请求
            const response = await axios.post('/register', {
                email,
                password: hashedPassword,
                code: verificationCode
            });

            if (response.data.code === 200) {
                // 弹框提示注册成功，3秒后跳转
                Toast.show({
                    icon: 'success',
                    content: '注册成功！',
                  })
                setTimeout(() => {
                    navigate('/login1');
                }, 1000);
            }
        } catch (error) {
            console.error('注册失败:', error);
            
            if (error.response && error.response.data) {
                if (error.response.data.message.includes('验证码')) {
                    setCodeError(error.response.data.message);
                } else if (error.response.data.message.includes('邮箱')) {
                    setEmailError(error.response.data.message);
                } else {
                    alert(error.response.data.message || '注册失败');
                }
            } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
                alert('请求超时，请检查网络连接');
            } else if (!error.response) {
                alert('网络错误，请检查网络连接');
            } else {
                alert('注册失败，请稍后重试');
            }
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className={styles.container}>
            {/* Curved header with logo */}
            <div className={styles.header}>
                <div className={styles.logo}>
                    <div className={styles.logoDot}></div>
                    <div className={styles.logoDot}></div>
                    <div className={styles.logoDot}></div>
                    <div className={styles.logoDot}></div>
                </div>
            </div>

            {/* Register content */}
            <div className={styles.content}>
                <h1 className={styles.title}>免费注册</h1>

                <form onSubmit={handleRegister}>
                    {/* Email field */}
                    <div className={`${styles.formGroup} ${emailError ? styles.hasError : ''}`}>
                        <label>电子邮件地址</label>
                        <div className={styles.inputContainer}>
                            <span className={styles.inputIcon}>
                                <svg viewBox="0 0 24 24" width="20" height="20">
                                    <path fill="#888888" d="M20,4H4C2.897,4,2,4.897,2,6v12c0,1.103,0.897,2,2,2h16c1.103,0,2-0.897,2-2V6C22,4.897,21.103,4,20,4z M20,6v0.511
                                    l-8,6.223l-8-6.222V6H20z M4,18V9.044l7.386,5.745C11.566,14.93,11.783,15,12,15s0.434-0.07,0.614-0.211L20,9.044L20.002,18H4z"></path>
                                </svg>
                            </span>
                            <input
                                type="text"
                                placeholder="输入你的电子邮箱..."
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                onBlur={() => handleBlur('email')}
                                required
                            />
                        </div>
                        {emailError && (
                            <div className={styles.errorMessage}>
                                <span className={styles.errorIcon}>⚠️</span>
                                {emailError}
                            </div>
                        )}
                    </div>

                    {/* Password field */}
                    <div className={`${styles.formGroup} ${passwordError ? styles.hasError : ''}`}>
                        <label>密码</label>
                        <div className={styles.inputContainer}>
                            <span className={styles.inputIcon}>
                                <svg viewBox="0 0 24 24" width="20" height="20">
                                    <path fill="#888888" d="M17,9V7c0-2.8-2.2-5-5-5S7,4.2,7,7v2c-1.7,0-3,1.3-3,3v7c0,1.7,1.3,3,3,3h10c1.7,0,3-1.3,3-3v-7
                                    C20,10.3,18.7,9,17,9z M9,7c0-1.7,1.3-3,3-3s3,1.3,3,3v2H9V7z M18,19c0,0.6-0.4,1-1,1H7c-0.6,0-1-0.4-1-1v-7c0-0.6,0.4-1,1-1
                                    h10c0.6,0,1,0.4,1,1V19z"></path>
                                </svg>
                            </span>
                            <input
                                type={showPassword ? "text" : "password"}
                                placeholder="输入你的密码..."
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                onBlur={() => handleBlur('password')}
                                required
                            />
                            <button
                                type="button"
                                className={styles.togglePassword}
                                onClick={() => setShowPassword(!showPassword)}
                            >
                                <svg viewBox="0 0 24 24" width="20" height="20" fill="#CCCCCC">
                                    <path d="M12,4C4.676,4,2,12,2,12s2.676,8,10,8s10-8,10-8S19.324,4,12,4z M12,16c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S14.206,16,12,16z M12,10c-1.103,0-2,0.897-2,2s0.897,2,2,2s2-0.897,2-2S13.103,10,12,10z"></path>
                                </svg>
                            </button>
                        </div>
                        {passwordError && (
                            <div className={styles.errorMessage}>
                                <span className={styles.errorIcon}>⚠️</span>
                                {passwordError}
                            </div>
                        )}
                    </div>

                    {/* Confirm Password field */}
                    <div className={`${styles.formGroup} ${confirmPasswordError ? styles.hasError : ''}`}>
                        <label>确认密码</label>
                        <div className={styles.inputContainer}>
                            <span className={styles.inputIcon}>
                                <svg viewBox="0 0 24 24" width="20" height="20">
                                    <path fill="#888888" d="M17,9V7c0-2.8-2.2-5-5-5S7,4.2,7,7v2c-1.7,0-3,1.3-3,3v7c0,1.7,1.3,3,3,3h10c1.7,0,3-1.3,3-3v-7
                                    C20,10.3,18.7,9,17,9z M9,7c0-1.7,1.3-3,3-3s3,1.3,3,3v2H9V7z M18,19c0,0.6-0.4,1-1,1H7c-0.6,0-1-0.4-1-1v-7c0-0.6,0.4-1,1-1
                                    h10c0.6,0,1,0.4,1,1V19z"></path>
                                </svg>
                            </span>
                            <input
                                type={showConfirmPassword ? "text" : "password"}
                                placeholder="确认你的密码..."
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                                onBlur={() => handleBlur('confirmPassword')}
                                required
                            />
                            <button
                                type="button"
                                className={styles.togglePassword}
                                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                            >
                                <svg viewBox="0 0 24 24" width="20" height="20" fill="#CCCCCC">
                                    <path d="M12,4C4.676,4,2,12,2,12s2.676,8,10,8s10-8,10-8S19.324,4,12,4z M12,16c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S14.206,16,12,16z M12,10c-1.103,0-2,0.897-2,2s0.897,2,2,2s2-0.897,2-2S13.103,10,12,10z"></path>
                                </svg>
                            </button>
                        </div>
                        {confirmPasswordError && (
                            <div className={styles.errorMessage}>
                                <span className={styles.errorIcon}>⚠️</span>
                                {confirmPasswordError}
                            </div>
                        )}
                    </div>

                    {/* Verification Code field */}
                    <div className={`${styles.formGroup} ${codeError ? styles.hasError : ''}`}>
                        <label>验证码</label>
                        <div className={styles.codeContainer}>
                            <div className={styles.inputContainer} style={{ flex: 1 }}>
                                <span className={styles.inputIcon}>
                                    <svg viewBox="0 0 24 24" width="20" height="20">
                                        <path fill="#888888" d="M17,3H7C5.9,3,5,3.9,5,5v14c0,1.1,0.9,2,2,2h10c1.1,0,2-0.9,2-2V5C19,3.9,18.1,3,17,3z M7,5h10v2H7V5z M7,19v-9h10v9H7z M16,11h-3v3h-2v-3H8v-2h3V6h2v3h3V11z"></path>
                                    </svg>
                                </span>
                                <input
                                    type="text"
                                    placeholder="输入验证码..."
                                    value={verificationCode}
                                    onChange={(e) => setVerificationCode(e.target.value)}
                                    onBlur={() => handleBlur('code')}
                                    required
                                />
                            </div>
                            <button 
                                type="button" 
                                className={`${styles.codeButton} ${isSendingCode ? styles.sending : ''}`}
                                onClick={handleSendCode}
                                disabled={countdown > 0 || isSendingCode || !validateEmail(email)}
                            >
                                {isSendingCode ? '发送中...' : 
                                 countdown > 0 ? `${countdown}秒后重新发送` : 
                                 retryCount > 0 ? '重新发送' : '获取验证码'}
                            </button>
                        </div>
                        {codeError && (
                            <div className={styles.errorMessage}>
                                <span className={styles.errorIcon}>⚠️</span>
                                {codeError}
                                {retryCount > 0 && codeError.includes('超时') && (
                                    <span className={styles.retryTip}>
                                        网络连接不稳定，请稍后再试
                                    </span>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Register button */}
                    <button 
                        type="submit" 
                        className={`${styles.registerButton} ${isSubmitting ? styles.submitting : ''}`}
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? '注册中...' : '注册'} <span className={styles.arrow}>›</span>
                    </button>
                </form>

                {/* Login link */}
                <div className={styles.footer}>
                    <p>
                        已经有账户？ <a href="/login1" className={styles.loginLink}>登录。</a>
                    </p>
                </div>
            </div>
        </div>
    );
}